package ink.tsg.javabase.thread;

import java.util.*;

public class EleSumTarget {
    private List<Integer> list;
    private Integer target;
    private int eleNum;
    private int listSize;
    public EleSumTarget(List<Integer> list,Integer target,Integer eleNum){
        if(!(eleNum>list.size())){
            this.list = list;
            this.target = target;
            this.eleNum = eleNum;
            this.listSize = list.size();
        }else{
            throw new RuntimeException("The number of elements exceeds the size of the array");
        }

    }
    public List<Integer> calcul(){
        if(this.listSize==this.eleNum){
            return calculSame();
        }else{
            return calculNotSame();
        }
    }
    /**
     * @Author Iter
     * @Description 计算list和期望累加数量不相等的情况
     * @Date 2021/1/27 14:41
     * @Param [list, target, eleNum]
     * @return java.util.List<java.lang.Integer>
     **/
    private List<Integer> calculNotSame() {
        // 先把list中的值和对应的下标都保存起来
        Map<Integer, Integer> hashMap = new HashMap<>();
        for(int i=0;i<this.listSize;i++){
            Integer integer = this.list.get(i);
            hashMap.put(integer,i);
        }
        // 排序数组
        Collections.sort(this.list);
        int sum = 0 ,i=0;
        ArrayList<Integer> result = new ArrayList<>();
        while (i<this.listSize-this.eleNum+1){
            for(int j=i;j<this.eleNum+i;j++){
                sum += this.list.get(j);
                result.add(hashMap.get(this.list.get(j)));
            }
            if(sum == this.target){
                return result;
            }else{
                result.clear();
                sum = 0;
                i++;
                continue;
            }
        }
        return null;
    }

    /**
     * @Author Iter
     * @Description 计算list和期望累加数量相等的情况
     * @Date 2021/1/27 14:41
     * @Param [list, target, eleNum]
     * @return java.util.List<java.lang.Integer>
     **/
    private List<Integer> calculSame() {
        int sum = 0;
        List<Integer> result = new ArrayList<>();
        for(int i=0;i<this.eleNum;i++){
            sum = this.list.get(i)+sum;
            result.add(i);
        }
        if(sum == this.target){
            return result;
        }else{
            return null;
        }
    }

}
